/**
 * @file CPvmCommands.cpp Implementácia triedy CPvmCommands.
 *
 * @author Martin Kosorinský.
 * @date 10.10.2009.
 */

#include "CPvmCommands.hpp"

int CPvmCommands::pvmRecv(int tid, int msg) {
    int bufid = pvm_recv(tid, msg);
    int length, tag, rtid;

    pvm_bufinfo(bufid, &length, &tag, &rtid);

    return tag;
}

void CPvmCommands::pvmPackBig(big * bp, int nitem, int stride) {
    char buffer[BYTE_BUFFER_SIZE];
    char sign;
    int size;

    for (int i = 0; i < nitem; i += stride) {
        size = big_to_bytes(BYTE_BUFFER_SIZE, bp[i], buffer, FALSE);
        // sem overenie uspesnoosti konverzie !!!
        // cerr << "Error: 'pvmPackBig': Zlyhal prevod big na bajty!" << endl;
        if (exsign(bp[i]) == -1)
            sign = PVM_BIG_NEGATIVE;
        else
            sign = PVM_BIG_POSITIVE;

        pvm_pkbyte(&sign, 1, 1);            // zabalime znaminko odosielaneho bigu
        pvm_pkint(&size, 1, 1);             // zabalime bytovu dlzku
        pvm_pkbyte(buffer, size, 1);        // zabalime samotne bajty
    }
}

void CPvmCommands::pvmUnpackBig(big * bp, int nitem, int stride) {
    char buffer[BYTE_BUFFER_SIZE];
    char sign;
    int size;
    int k = 0;

    for (int i = 0; i < nitem; i++) {
        pvm_upkbyte(&sign, 1, 1);           // ziskame znamienko bigu
        pvm_upkint(&size, 1, 1);            // ziskame dlzku pola bajtov
        pvm_upkbyte(buffer, size, 1);       // pole bajtov -> buffer
        bytes_to_big(size, buffer, bp[i]);  // konverzia pola bajtov na premennu typu big

        // sem overenie uspesnoosti konverzie !!!
        // cerr << "Error: 'pvmUn[pPackBig': Zlyhal prevod bajtov na big!" << endl;
        if (sign == PVM_BIG_NEGATIVE)
            insign(MINUS, bp[i]);
        else
            insign(PLUS, bp[i]);

        k += stride;
    }
}
